<template>
    <div class="user-management">
        <!-- 搜索和操作区域 -->
        <div class="search-operation">
            <el-card shadow="never">
                <div class="search-form">
                    <el-form :model="searchForm" inline>
                        <el-form-item label="用户ID">
                            <el-input v-model="searchForm.user_id" placeholder="请输入用户ID" clearable
                                style="width: 120px" />
                        </el-form-item>
                        <el-form-item label="昵称">
                            <el-input v-model="searchForm.nickname" placeholder="请输入昵称" clearable
                                style="width: 150px" />
                        </el-form-item>
                        <el-form-item label="手机号">
                            <el-input v-model="searchForm.phone" placeholder="请输入手机号" clearable style="width: 150px" />
                        </el-form-item>
                        <el-form-item label="邮箱">
                            <el-input v-model="searchForm.email" placeholder="请输入邮箱" clearable style="width: 200px" />
                        </el-form-item>
                        <el-form-item label="认证状态">
                            <el-select v-model="searchForm.verification_status" clearable placeholder="请选择">
                                <el-option label="未认证" :value="0" />
                                <el-option label="已认证" :value="1" />
                                <el-option label="认证中" :value="2" />
                            </el-select>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="handleSearch" :icon="Search">搜索</el-button>
                            <el-button @click="handleReset" :icon="Refresh">重置</el-button>
                        </el-form-item>
                    </el-form>
                </div>
            </el-card>
        </div>

        <!-- 用户列表 -->
        <div class="user-list">
            <el-card shadow="never">
                <template #header>
                    <div class="table-header">
                        <span>用户列表</span>
                        <div>
                            <el-button type="primary" @click="handleCreate" :icon="Plus">新增用户</el-button>
                            <el-button @click="exportUsers" :icon="Download">导出数据</el-button>
                        </div>
                    </div>
                </template>

                <el-table :data="userList" v-loading="loading" border stripe style="width: 100%">
                    <el-table-column prop="user_id" label="用户ID" width="80" align="center" />
                    <el-table-column prop="avatar" label="头像" width="80" align="center">
                        <template #default="{ row }">
                            <el-avatar :size="40" :src="row.avatar" v-if="row.avatar">
                                {{ row.nickname ? row.nickname.charAt(0) : 'U' }}
                            </el-avatar>
                            <el-avatar :size="40" v-else>
                                {{ row.nickname ? row.nickname.charAt(0) : 'U' }}
                            </el-avatar>
                        </template>
                    </el-table-column>
                    <el-table-column prop="nickname" label="昵称" min-width="120" />
                    <el-table-column prop="phone" label="手机号" width="130" />
                    <el-table-column prop="email" label="邮箱" min-width="180" />
                    <el-table-column prop="real_name" label="真实姓名" width="100" />
                    <el-table-column prop="student_id" label="学号" width="120" />
                    <el-table-column prop="verification_status" label="认证状态" width="100" align="center">
                        <template #default="{ row }">
                            <el-tag :type="getVerificationStatusType(row.verification_status)" size="small">
                                {{ getVerificationStatusText(row.verification_status) }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="gender" label="性别" width="80" align="center">
                        <template #default="{ row }">
                            <span>{{ getGenderText(row.gender) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="city" label="城市" width="100" />
                    <el-table-column prop="company" label="公司" min-width="120" />
                    <el-table-column prop="position" label="职位" min-width="120" />
                    <el-table-column prop="created_at" label="注册时间" width="180">
                        <template #default="{ row }">
                            {{ formatDate(row.created_at) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="200" fixed="right" align="center">
                        <template #default="{ row }">
                            <el-button size="small" type="primary" link @click="handleEdit(row)" :icon="Edit">
                                编辑
                            </el-button>
                            <el-button size="small" type="warning" link @click="handleView(row)" :icon="View">
                                详情
                            </el-button>
                            <el-button size="small" type="danger" link @click="handleDelete(row.user_id)"
                                :icon="Delete">
                                删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <!-- 分页 -->
                <div class="pagination">
                    <el-pagination v-model:current-page="pagination.page" v-model:page-size="pagination.pageSize"
                        :page-sizes="[10, 20, 50, 100]" :total="pagination.total"
                        layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
                        @current-change="handleCurrentChange" />
                </div>
            </el-card>
        </div>

        <!-- 用户详情对话框 -->
        <el-dialog v-model="detailDialogVisible" title="用户详情" width="600px" destroy-on-close>
            <el-descriptions :column="2" border v-if="currentUser">
                <el-descriptions-item label="用户ID">{{ currentUser.user_id }}</el-descriptions-item>
                <el-descriptions-item label="昵称">{{ currentUser.nickname || '-' }}</el-descriptions-item>
                <el-descriptions-item label="手机号">{{ currentUser.phone }}</el-descriptions-item>
                <el-descriptions-item label="邮箱">{{ currentUser.email }}</el-descriptions-item>
                <el-descriptions-item label="真实姓名">{{ currentUser.real_name || '-' }}</el-descriptions-item>
                <el-descriptions-item label="学号">{{ currentUser.student_id || '-' }}</el-descriptions-item>
                <el-descriptions-item label="性别">{{ getGenderText(currentUser.gender) }}</el-descriptions-item>
                <el-descriptions-item label="认证状态">
                    <el-tag :type="getVerificationStatusType(currentUser.verification_status)" size="small">
                        {{ getVerificationStatusText(currentUser.verification_status) }}
                    </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="城市">{{ currentUser.city || '-' }}</el-descriptions-item>
                <el-descriptions-item label="公司">{{ currentUser.company || '-' }}</el-descriptions-item>
                <el-descriptions-item label="职位">{{ currentUser.position || '-' }}</el-descriptions-item>
                <el-descriptions-item label="个人简介" :span="2">
                    {{ currentUser.bio || '-' }}
                </el-descriptions-item>
                <el-descriptions-item label="地址" :span="2">
                    {{ currentUser.address || '-' }}
                </el-descriptions-item>
                <el-descriptions-item label="注册时间">{{ formatDate(currentUser.created_at) }}</el-descriptions-item>
                <el-descriptions-item label="更新时间">{{ formatDate(currentUser.updated_at) }}</el-descriptions-item>
            </el-descriptions>
        </el-dialog>

        <!-- 新增/编辑用户对话框 -->
        <el-dialog v-model="formDialogVisible" :title="formTitle" width="500px" destroy-on-close>
            <el-form ref="userFormRef" :model="userForm" :rules="userFormRules" label-width="100px">
                <!-- 新增用户时只显示三个字段 -->
                <template v-if="isCreate">
                    <el-form-item label="手机号" prop="phone">
                        <el-input v-model="userForm.phone" placeholder="请输入手机号" />
                    </el-form-item>
                    <el-form-item label="邮箱" prop="email">
                        <el-input v-model="userForm.email" placeholder="请输入邮箱" />
                    </el-form-item>
                    <el-form-item label="密码" prop="password">
                        <el-input v-model="userForm.password" type="password" placeholder="请输入密码" show-password />
                    </el-form-item>
                </template>

                <!-- 编辑用户时显示完整表单 -->
                <template v-else>
                    <el-form-item label="昵称" prop="nickname">
                        <el-input v-model="userForm.nickname" placeholder="请输入昵称" />
                    </el-form-item>
                    <el-form-item label="手机号" prop="phone">
                        <el-input v-model="userForm.phone" placeholder="请输入手机号" />
                    </el-form-item>
                    <el-form-item label="邮箱" prop="email">
                        <el-input v-model="userForm.email" placeholder="请输入邮箱" />
                    </el-form-item>
                    <el-form-item label="密码">
                        <el-input v-model="userForm.password" type="password" placeholder="留空则不修改密码" show-password />
                    </el-form-item>
                    <el-form-item label="真实姓名">
                        <el-input v-model="userForm.real_name" placeholder="请输入真实姓名" />
                    </el-form-item>
                    <el-form-item label="学号">
                        <el-input v-model="userForm.student_id" placeholder="请输入学号" />
                    </el-form-item>
                    <el-form-item label="性别">
                        <el-radio-group v-model="userForm.gender">
                            <el-radio :label="1">男</el-radio>
                            <el-radio :label="2">女</el-radio>
                            <el-radio :label="0">未知</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="认证状态">
                        <el-select v-model="userForm.verification_status" placeholder="请选择认证状态">
                            <el-option label="未认证" :value="0" />
                            <el-option label="已认证" :value="1" />
                            <el-option label="认证中" :value="2" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="城市">
                        <el-input v-model="userForm.city" placeholder="请输入城市" />
                    </el-form-item>
                    <el-form-item label="公司">
                        <el-input v-model="userForm.company" placeholder="请输入公司" />
                    </el-form-item>
                    <el-form-item label="职位">
                        <el-input v-model="userForm.position" placeholder="请输入职位" />
                    </el-form-item>
                    <el-form-item label="个人简介">
                        <el-input v-model="userForm.bio" type="textarea" :rows="3" placeholder="请输入个人简介" maxlength="255"
                            show-word-limit />
                    </el-form-item>
                    <el-form-item label="地址">
                        <el-input v-model="userForm.address" placeholder="请输入地址" />
                    </el-form-item>
                </template>
            </el-form>
            <template #footer>
                <el-button @click="formDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleSubmit" :loading="formLoading">
                    确定
                </el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
    Search,
    Refresh,
    Plus,
    Download,
    Edit,
    View,
    Delete
} from '@element-plus/icons-vue'
import { getUserList, updateUser, getUserDetail, deleteUser } from '@/api/user'
import { Register } from '@/api/account'
import { validateEmail, validatePhone } from '@/utils/validate'

const router = useRouter()

// 验证规则函数
const validatePhoneRule = (rule, value, callback) => {
    if (!value) {
        callback(new Error('请输入手机号'))
    } else if (!validatePhone(value)) {
        callback(new Error('请输入正确的手机号格式'))
    } else {
        callback()
    }
}

const validateEmailRule = (rule, value, callback) => {
    if (!value) {
        callback(new Error('请输入邮箱'))
    } else if (!validateEmail(value)) {
        callback(new Error('请输入正确的邮箱格式'))
    } else {
        callback()
    }
}

// 表单验证规则
const userFormRules = {
    phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { validator: validatePhoneRule, trigger: 'blur' }
    ],
    email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { validator: validateEmailRule, trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
    ]
}

// 响应式数据
const loading = ref(false)
const detailDialogVisible = ref(false)
const formDialogVisible = ref(false)
const formLoading = ref(false)
const userFormRef = ref()
const currentUser = ref(null)
const userList = ref([])

// 搜索表单
const searchForm = reactive({
    user_id: '',
    nickname: '',
    phone: '',
    email: '',
    verification_status: ''
})

// 分页配置
const pagination = reactive({
    page: 1,
    pageSize: 10,
    total: 0
})

// 用户表单
const userForm = reactive({
    phone: '',
    email: '',
    password: '',
    nickname: '',
    real_name: '',
    student_id: '',
    gender: 0,
    verification_status: 0,
    city: '',
    company: '',
    position: '',
    bio: '',
    address: ''
})

// 计算属性
const formTitle = computed(() => {
    return isCreate.value ? '新增用户' : '编辑用户'
})

const isCreate = computed(() => {
    return !currentUser.value?.user_id
})

// 监听表单对话框显示状态，重置表单
watch(formDialogVisible, (newVal) => {
    if (!newVal) {
        resetForm()
    }
})

// 工具函数
const getVerificationStatusType = (status) => {
    const types = {
        0: 'info',    // 未认证
        1: 'success', // 已认证
        2: 'warning'  // 认证中
    }
    return types[status] || 'info'
}

const getVerificationStatusText = (status) => {
    const texts = {
        0: '未认证',
        1: '已认证',
        2: '认证中'
    }
    return texts[status] || '未知'
}

const getGenderText = (gender) => {
    const texts = {
        0: '未知',
        1: '男',
        2: '女'
    }
    return texts[gender] || '未知'
}

const formatDate = (dateString) => {
    if (!dateString) return '-'
    try {
        const date = new Date(dateString)
        return date.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
        }).replace(/\//g, '-')
    } catch (error) {
        return dateString
    }
}

// 页面加载时获取用户列表
onMounted(() => {
    fetchUsers()
})

const fetchUsers = async () => {
    try {
        loading.value = true

        const params = {
            page: pagination.page,
            pageSize: pagination.pageSize,
            ...searchForm
        }

        // 清理空值参数
        Object.keys(params).forEach(key => {
            if (params[key] === '' || params[key] === null || params[key] === undefined) {
                delete params[key]
            }
        })

        console.log('请求参数:', params) // 调试日志

        const response = await getUserList(params)
        console.log('API响应:', response) // 调试日志

        if (response.code === 0) {
            // 更健壮的数据处理
            if (response.data && Array.isArray(response.data.list)) {
                userList.value = response.data.list
                pagination.total = response.data.total || 0
            } else if (Array.isArray(response.data)) {
                userList.value = response.data
                pagination.total = response.data.length
            } else {
                userList.value = []
                pagination.total = 0
                console.warn('意外的响应数据结构:', response.data)
            }
            
            console.log('处理后的用户列表:', userList.value) // 调试日志
            console.log('总数:', pagination.total) // 调试日志
        } else {
            ElMessage.error(response.msg || '获取用户列表失败')
        }
    } catch (error) {
        console.error('获取用户列表错误:', error) // 详细错误日志
        if (error.response?.status !== 401) {
            ElMessage.error('网络错误，请稍后重试')
        }
    } finally {
        loading.value = false
    }
}

// 搜索用户
const handleSearch = () => {
    pagination.page = 1
    fetchUsers()
}

// 重置搜索
const handleReset = () => {
    Object.keys(searchForm).forEach(key => {
        searchForm[key] = ''
    })
    pagination.page = 1
    fetchUsers()
}

// 分页大小改变
const handleSizeChange = (newSize) => {
    pagination.pageSize = newSize
    pagination.page = 1
    fetchUsers()
}

// 当前页改变
const handleCurrentChange = (newPage) => {
    pagination.page = newPage
    fetchUsers()
}

// 查看用户详情
const handleView = async (user) => {
    try {
        const response = await getUserDetail(user.user_id)
        if (response.code === 0) {
            currentUser.value = response.data
            detailDialogVisible.value = true
        } else {
            ElMessage.error(response.msg || '获取用户详情失败')
        }
    } catch (error) {
        ElMessage.error('获取用户详情失败')
        console.error('获取用户详情失败:', error)
    }
}

// 新增用户
const handleCreate = () => {
    currentUser.value = null
    resetForm()
    formDialogVisible.value = true
}

// 编辑用户
const handleEdit = async (user) => {
    try {
        const response = await getUserDetail(user.user_id)
        if (response.code === 0) {
            currentUser.value = response.data
            Object.keys(userForm).forEach(key => {
                if (currentUser.value[key] !== undefined) {
                    userForm[key] = currentUser.value[key]
                }
            })
            // 编辑时不需要密码字段
            userForm.password = ''
            formDialogVisible.value = true
        } else {
            ElMessage.error(response.msg || '获取用户信息失败')
        }
    } catch (error) {
        ElMessage.error('获取用户信息失败')
        console.error('获取用户信息失败:', error)
    }
}

// 删除用户
const handleDelete = async (userId) => {
    try {
        await ElMessageBox.confirm(
            '确定要删除该用户吗？此操作不可恢复！',
            '警告',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )

        const response = await deleteUser(userId)
        if (response.code === 0) {
            ElMessage.success('删除用户成功')
            fetchUsers()
        } else {
            ElMessage.error(response.msg || '删除用户失败')
        }
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('删除用户失败')
            console.error('删除用户失败:', error)
        }
    }
}

// 提交表单（新增/编辑）
const handleSubmit = async () => {
    if (!userFormRef.value) return

    try {
        await userFormRef.value.validate()
        formLoading.value = true

        let response

        if (isCreate.value) {
            // 新增用户 - 调用注册接口
            const registerData = {
                phone: userForm.phone,
                email: userForm.email,
                password: userForm.password
            }

            response = await Register(registerData)

            if (response.code === 0) {
                ElMessage.success('创建用户成功')
                formDialogVisible.value = false
                fetchUsers()
            } else {
                ElMessage.error(response.msg || '创建用户失败')
            }
        } else {
            // 编辑用户 - 准备提交数据
            const submitData = { ...userForm }

            // 如果密码为空，则不更新密码
            if (!submitData.password) {
                delete submitData.password
            }

            response = await updateUser(currentUser.value.user_id, submitData)

            if (response.code === 0) {
                ElMessage.success('更新用户成功')
                formDialogVisible.value = false
                fetchUsers()
            } else {
                ElMessage.error(response.msg || '更新用户失败')
            }
        }
    } catch (error) {
        if (error.errors) {
            ElMessage.error('请完善表单信息')
        } else {
            ElMessage.error(isCreate.value ? '创建用户失败' : '更新用户失败')
            console.error('表单提交失败:', error)
        }
    } finally {
        formLoading.value = false
    }
}

// 导出用户数据
const exportUsers = () => {
    ElMessage.info('导出功能开发中...')
    // 实际项目中这里可以实现导出Excel等功能
}

// 重置表单
const resetForm = () => {
    Object.keys(userForm).forEach(key => {
        if (key === 'gender') {
            userForm[key] = 0
        } else if (key === 'verification_status') {
            userForm[key] = 0
        } else {
            userForm[key] = ''
        }
    })

    if (userFormRef.value) {
        userFormRef.value.clearValidate()
    }
}
</script>

<style scoped>
.user-management {
    padding: 20px;
}

.search-operation {
    margin-bottom: 20px;
}

.search-form {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
}

.table-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.user-list {
    margin-bottom: 20px;
}

.pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}

:deep(.el-descriptions__label) {
    width: 100px;
    font-weight: bold;
}

:deep(.el-descriptions__content) {
    width: calc(100% - 100px);
}
</style>